package cn.zhuo.knowledge.util.hutool.crypto.secure;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * <p>
 *
 * @author z2huo
 */
class AESTest {

    public static void main(String[] args) {

        noKeySameAes();

        System.out.println("========================================");

        getAESKey();

        System.out.println("========================================");

        key();

        System.out.println("========================================");

        keyDiffAES();
    }

    public static void noKeySameAes() {
        //String string = "hello world";
        String string = "token:buy:29:10085:5ac6542b-64b1-4d41-91b9-e6c55849bb7f";

        AES aes = SecureUtil.aes();

        // 下面的加密和解密必须使用相同的 aes 对象，因为没有指定 秘钥
        byte[] encryptByteArray = aes.encrypt(string);
        System.out.println(new String(encryptByteArray));
        String decryptStr = aes.decryptStr(encryptByteArray);
        System.out.println(decryptStr);

        System.out.println("===== base64 =====");
        String encode = Base64.encode(encryptByteArray);
        System.out.println(encode);
        String encryptBase64 = aes.encryptBase64(string);
        System.out.println(encryptBase64);

    }

    public static void getAESKey() {
        SecretKey secretKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), 128);
        System.out.println(secretKey.getAlgorithm());
        System.out.println(Arrays.toString(secretKey.getEncoded()));
        System.out.println(new String(secretKey.getEncoded(), StandardCharsets.UTF_8));
        System.out.println(secretKey.getFormat());
    }

    public static void key() {
        String string = "hello world";

        String key = "20251016165206hh";

        AES aes = SecureUtil.aes(key.getBytes(StandardCharsets.UTF_8));

        byte[] encryptByteArray = aes.encrypt(string);
        System.out.println(new String(encryptByteArray));
        String decryptStr = SecureUtil.aes(key.getBytes(StandardCharsets.UTF_8)).decryptStr(encryptByteArray);
        System.out.println(decryptStr);
    }

    public static void keyDiffAES() {
        String string = "hello world";

        String key = "20251016165206hh";

        byte[] encryptByteArray = SecureUtil.aes(key.getBytes(StandardCharsets.UTF_8)).encrypt(string);
        System.out.println(new String(encryptByteArray));
        String decryptStr = SecureUtil.aes(key.getBytes(StandardCharsets.UTF_8)).decryptStr(encryptByteArray);
        System.out.println(decryptStr);
    }

}
